958. Check Completeness of a Binary Tree

Check Completeness of a Binary Tree

Given a binary tree, determine if it is a complete binary tree. Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example 1:

img

1
2
3
Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Example 2:

img

1
2
3
Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.

解法一:层次遍历

思路:层次遍历每一个节点,当遇到第一个叶子节点或最后一个非叶子节点时,判断此后的每一个节点都是叶子节点。
对于每一个节点,如果它是非叶子节点,那么它要么有两个孩子节点,否则,只有左孩子节点,如果一个节点有右孩子而没有左孩子,则该节点不是完全二叉树上的节点。
当一个节点只有左孩子,没有右孩子,则该节点是最后一个非叶子节点;如果一个节点既没有左孩子节点也没有右孩子节点,则该节点是第一个叶子节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
if(root == nullptr){
return true;
}
queue<TreeNode*> q;
TreeNode* node = nullptr;
int cur = 1;
int next = 0;
q.push(root);
while(!q.empty()){
node = q.front();
q.pop();
if(node->left !=nullptr){
q.push(node->left);
++next;
}
if(node->right !=nullptr){
if(node->left == nullptr){
return false;
}
q.push(node->right);
++next;
} // first leaf or last not leaf
else{
while(!q.empty()) {
node = q.front();
q.pop();
if(node->left != nullptr || node->right != nullptr){
return false;
}
}
break;
}

if(--cur==0){
cur = next;
next = 0;
}
}

// only one node
return true;
}
};

解法二:

通过比较一棵完全二叉树中应有的节点总数和当前二叉树中的节点总数来判断是否是完全二叉树。这种思路是可行的,但是代码无法通过所有测试用例,原因是当二叉树的深度过深时,start的值会超出int允许的范围。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
int cnt1 = countNodes(root);
int cnt2 = countByLevel(root, 1) ;
return cnt1 == cnt2;
}

int countNodes(TreeNode* root){
if(root == nullptr){
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}

int countByLevel(TreeNode* root, int start){
if(root == nullptr){
return 0;
}
int left = countByLevel(root->left, start * 2);
int right = countByLevel(root->right, start * 2 + 1);
return max(max(left, right), start);
}
};

相关题目

958. Check Completeness of a Binary Tree
222. Count Complete Tree Nodes
919. Complete Binary Tree Inserter